<script>
	import storage from "@/utils/storage.js"
	import dayjs from "dayjs"
	import {
		mapMutations,
		mapGetters,
		mapActions
	} from 'vuex'
	import {
		InitBlueTooth,
		CreateBlueToothConnection,
		ReadBlueTooth
	} from "@/utils/BLE.js"
	import {
		UpdateDevice,
		SendBlueTooth
	} from "@/api/device.js"
	import {
		UpdateCid
	} from "@/api/login.js"
	import {
		perwarnTest
	} from "@/api/message.js"
	export default {
		data() {
			return {}
		},
		onLaunch() {
			this.HistoryData = {
				dataone: [],
				datatwo: [],
				deviceId: ''
			}
			this.Timer = null
			let that = this
			// 监听蓝牙数据
			if (storage.getToken()) {
				that.timerController()
				// 监听蓝牙是否可用  手机蓝牙断开或者连接
				that.onBlueToothState()
				that.onBLECharacteristicValueChange()
				that.initBlueToothDevice()
				this.ActionUserList(storage.getUserInfo())
				that.ActionDeviceList().then((res) => {
					that.getDeviceState = true
					that.currentBlueToothDevice('app')
				})
			}
			uni.$on("LOGIN", () => {
				that.timerController()
				// 监听蓝牙是否可用  手机蓝牙断开或者连接
				that.onBlueToothState()
				that.onBLECharacteristicValueChange()
				that.initBlueToothDevice()
				that.ActionDeviceList().then((res) => {
					that.getDeviceState = true
					that.currentBlueToothDevice()
				})
			})
		},
		onShow: function() {
			console.log('App Show')
			setTimeout(() => {
				uni.hideTabBar({
					complete(res) {
						console.log(res)
					}
				})
			}, 1000)
		},
		onHide: function() {
			console.log('App Hide')
			uni.closeBluetoothAdapter({
				success(res) {
					console.log('closeBluetoothAdapter', res)
				}
			})
		},
		computed: {
			...mapGetters([
				'BlueAvailable', 'AppDevice', 'BlueBodyInfo', 'StepCounting', 'UserInfo'
			])
		},
		methods: {
			...mapMutations(['SetBlueAvailable', 'SetCurrentLinkDevice', 'SetStepCounting']),
			...mapActions(['WriteBlueTooth', 'SearchAndGetBlueToothList', 'ActionBlueBodyInfo', 'ActionDeviceList',
				'ActionCurrentLink',
				'ActionElectric', 'ActionBuleList', 'ActionUserList', 'SetupCurrentDeviceState'
			]),
			// 初始化蓝牙,搜索蓝牙设备列表
			initBlueToothDevice() {
				let that = this
				if (that.UserInfo.utype === 1) {
					that.initBlueState = true
					that.currentBlueToothDevice()
				} else {
					InitBlueTooth().then(() => {
						that.initBlueState = true
						that.currentBlueToothDevice()
						this.SearchAndGetBlueToothList()
					})
				}
			},
			// 判断当前蓝牙连接设备
			currentBlueToothDevice(type) {
				let that = this
				if (!(that.getDeviceState === true && this.initBlueState === true)) return
				let currentDevice = storage.getCurrentDevice()
				if (!currentDevice) return
				let findDevice = this.AppDevice.filter((item) => {
					if (item.deviceId === currentDevice.deviceId) {
						return item
					}
				})
				if (findDevice.length === 0) {
					if (type === 'app') {
						that.SetupCurrentDeviceState('')
					}
					return
				}
				if (that.UserInfo.utype === 1) {
					that.SetupCurrentDeviceState({
						...currentDevice,
						state: 'link'
					}, that)
					return
				}
				that.SetupCurrentDeviceState({
					...currentDevice,
					state: 'ing'
				}, that)
				console.log("创建连接----app页面")
				CreateBlueToothConnection(currentDevice).then((res) => {
					// -------设置当前设备---------
					that.currentDivice = {
						deviceId: res.device.deviceId,
						name: res.device.name,
						serviceId: res.service.uuid,
						characteristicId: res.c.uuid,
						state: 'link'
					}
					that.SetupCurrentDeviceState(that.currentDivice, that)
					that.onBLECharacteristicValueChange()
					ReadBlueTooth(res.device, res.service, res.c)
					setTimeout(() => {
						// 给设备设置时间
						// WriteBlueTooth('time', that.currentDivice)
						// 同步时间
						// WriteBlueTooth('time')
						// 获取设备电量
						this.WriteBlueTooth('electric')
						// 一件测量
						// this.WriteBlueTooth('test')
						// 同步数据
						this.WriteBlueTooth('tongbu')
					}, 5000)
				}, (res) => {
					console.log('**fail', res)
					uni.showToast({
						title: "无法连接当前设备",
						icon: "none"
					})
					that.SetupCurrentDeviceState({
						...currentDevice,
						state: 'no'
					}, that)
				})
			},
			onBlueToothState() {
				let that = this
				uni.getBluetoothAdapterState({
					success(res) {
						that.SetBlueAvailable(res.available)
					}
				})
				uni.onBluetoothAdapterStateChange(function(res) {
					if (that.BlueAvailable !== res.available) {
						that.SetBlueAvailable(res.available)
						if (res.available === true) {
							that.initBlueToothDevice()
						} else {
							that.ActionBuleList('')
							that.SetupCurrentDeviceState('')
							uni.showToast({
								title: '请打开本机蓝牙',
								icon: "none"
							})
						}
					}
				})
			},
			// 监听低功耗蓝牙设备的特征值变化事件
			onBLECharacteristicValueChange() {
				let that = this
				uni.onBLECharacteristicValueChange((bluedata) => {
					// console.log(bluedata)
					let resultObj = that.ab2hex(bluedata.value)
					let result = resultObj.hexArr
					let bitArr = resultObj.bitArr
					console.log(result)
					console.log(bitArr)
					if (result[4] === '11') {
						// bytes[4] == 0x11 
						// bytes[5] 无意义
						// bytes[6] 跌倒次数
						// console.log('跌倒 ' + bitArr[6].toString(10))
					} else if (result[4] === '31') {
						// bytes[4] == 0x31 
						// bytes[5] == 0x09（单次） 或  bytes[5] == 0x0A（实时）
						// bytes[6] 心率测量值
						// if (result[5] === '09') {
						// 	console.log('单次-心率测量值 ' + bitArr[6].toString(10))
						// }
						// if (result[5] === '0a') {
						// 	console.log('实时-心率测量值  ' + bitArr[6].toString(10))
						// }
						// if (result[5] === '11') {
						// 	console.log('实时-血氧测量值  ' + bitArr[6].toString(10))
						// }
						// if (result[5] === '12') {
						// 	console.log('实时-血氧测量值  ' + bitArr[6].toString(10))
						// }
						// if (result[5] === '21') {
						// 	console.log('实时-血压测量值  ' + bitArr[6].toString(10))
						// }
						// if (result[5] === '22') {
						// 	console.log('实时-血压测量值  ' + bitArr[6].toString(10))
						// }
					} else if (result[4] === '21') {
						// console.log('心率值:' + bitArr[6].toString(10))
						// console.log('血氧值:' + bitArr[7].toString(10))
						// console.log('高血压值:' + bitArr[8].toString(10))
						// console.log('低血压值:' + bitArr[9].toString(10))
					} else if (result[4] === '32') {
						console.log('心率值:' + bitArr[6].toString(10))
						console.log('血氧值:' + bitArr[7].toString(10))
						console.log('高血压值:' + bitArr[8].toString(10))
						console.log('低血压值:' + bitArr[9].toString(10))
						if (that.BlueBodyInfo.test === 'ing') {
							console.log('一键测量数据给后台进行预警')
							// perwarnTest({
							// 	xinlv: bitArr[6].toString(10),
							// 	xueyang: bitArr[7].toString(10),
							// 	gaoya: bitArr[8].toString(10),
							// 	diya: bitArr[9].toString(10),
							// 	prewarnHealthDeviceId: bluedata.deviceId
							// }).then((res) => {
							// 	console.log(res)
							// })
						}
						that.ActionBlueBodyInfo({
							xinlv: bitArr[6].toString(10),
							xueyang: bitArr[7].toString(10),
							gaoya: bitArr[8].toString(10),
							diya: bitArr[9].toString(10),
							test: 'finish'
						})
					} else if (result[4] === '52') {
						let date = '20' + bitArr[6].toString(10) + '-' +
							bitArr[7].toString(10) + '-' +
							bitArr[8].toString(10) + ' ' +
							bitArr[9].toString(10) + ':' + bitArr[10].toString(10)
						let type = bitArr[11].toString(10)
						let time = parseInt((bitArr[12] << 8).toString(10)) + parseInt(bitArr[13].toString(10))
						console.log(date, '--', type, '--', time)
						let params = {}
						params = {
							"date": date,
							"type": type,
							"time": time,
						}
						that.HistoryData.datatwo.push(params)
						clearTimeout(that.Timer)
						that.Timer = setTimeout(() => {
							console.log('--------发送请求---------')
							that.HistoryData.deviceId = bluedata.deviceId
							console.log(that.HistoryData)
							console.log(JSON.stringify(that.HistoryData))
							SendBlueTooth(that.HistoryData).then((res) => {
								console.log('^^蓝牙数据添加成功^^')
							})
						}, 1500)
					} else if (result[4] === '51') {
						let params = {}
						if (result[5] == '11') {
							// console.log('心率:' + bitArr[6].toString(10) + '-' +
							// 	bitArr[7].toString(10) + '-' +
							// 	bitArr[8].toString(10) + ' ' +
							// 	bitArr[9].toString(10) + '-' +
							// 	bitArr[10].toString(10) + '------' +
							// 	bitArr[11].toString(10))
						} else if (result[5] == '12') {
							// console.log('心氧:' + bitArr[6].toString(10) + '-' +
							// 	bitArr[7].toString(10) + '-' +
							// 	bitArr[8].toString(10) + ' ' +
							// 	bitArr[9].toString(10) + '-' +
							// 	bitArr[10].toString(10) + '------' +
							// 	bitArr[11].toString(10))
						} else if (result[5] == '14') {
							// console.log('血压:' + bitArr[6].toString(10) + '-' +
							// 	bitArr[7].toString(10) + '-' +
							// 	bitArr[8].toString(10) + ' ' +
							// 	bitArr[9].toString(10) + '-' +
							// 	bitArr[10].toString(10) + '------' +
							// 	bitArr[11].toString(10))
						} else if (result[5] == '20') {
							let time = '20' + bitArr[6].toString(10) + '-' +
								bitArr[7].toString(10) + '-' +
								bitArr[8].toString(10) + ' ' +
								bitArr[9].toString(10)
							let step = parseInt((bitArr[10] << 16).toString(10)) + parseInt((bitArr[11] << 8)
								.toString(10)) + parseInt(bitArr[12].toString(10))
							step = step.toString(10)
							let kcal = parseInt((bitArr[13] << 16).toString(10)) + parseInt((bitArr[14] << 8)
								.toString(10)) + parseInt(bitArr[15].toString(10))
							kcal = kcal.toString(10)
							// console.log('时间:' + time)
							// console.log('计步：' + step)
							// console.log('卡路里:' + kcal)
							// console.log('心率：' + bitArr[16].toString(10))
							// console.log('心氧:' + bitArr[17].toString(10))
							// console.log('收缩压：' + bitArr[18].toString(10))
							// console.log('舒张压：' + bitArr[19].toString(10))
							let params = {}
							params = {
								newTime: time,
								step: step,
								kcal: kcal,
								xinlv: bitArr[16].toString(10),
								xueyang: bitArr[17].toString(10),
								shousuoya: bitArr[18].toString(10),
								shuzhangya: bitArr[19].toString(10),
							}
							that.HistoryData.dataone.push(params)
							clearTimeout(that.Timer)
							that.Timer = setTimeout(() => {
								that.HistoryData.deviceId = bluedata.deviceId
								console.log('--------发送请求---------')
								console.log(that.HistoryData)
								console.log(JSON.stringify(that.HistoryData))
								SendBlueTooth(that.HistoryData).then((res) => {
									console.log('^^蓝牙数据添加成功^^')
								})
							}, 1500)
						} else {
							let step = parseInt((bitArr[6] << 16).toString(10)) + parseInt((bitArr[7] << 8)
								.toString(10)) + parseInt(bitArr[8].toString(10))
							step = step.toString(10)
							console.log('计步：' + step)
							let kcal = parseInt((bitArr[9] << 16).toString(10)) + parseInt((bitArr[10] << 8)
								.toString(10)) + parseInt(bitArr[11].toString(10))
							kcal = kcal.toString(10)
							console.log('卡路里:' + kcal)
							console.log('浅睡小时值:' + bitArr[12].toString(10))
							console.log('浅睡分钟值：' + bitArr[13].toString(10))
							console.log('深睡小时值：' + bitArr[14].toString(10))
							console.log('深睡分钟值：' + bitArr[15].toString(10))
							console.log('醒来次数' + bitArr[16].toString(10))
							params.step = step
							params.kcal = kcal
							params.shallowhoue = bitArr[12].toString(10)
							params.shallowminute = bitArr[13].toString(10)
							params.deephoue = bitArr[14].toString(10)
							params.deepminute = bitArr[15].toString(10)
							console.log('^^^^^^^^^^^^^^^^^^^', params)
							that.ActionBlueBodyInfo(params)
							// 判断是否是计步状态
							console.log('???????????????', that.StepCounting.state, step, kcal)
							if (that.StepCounting.state) {
								if (that.StepCounting.state === 'perstart') {
									console.log('???????????????', that.StepCounting.state, step, kcal)
									that.SetStepCounting({
										state: 'start',
										startStep: step,
										startKcal: kcal,
										startTime: new Date().getTime(),
									})
								}
								if (that.StepCounting.state === 'end') {
									console.log('???????????????', that.StepCounting.state, step, kcal)
									that.SetStepCounting({
										state: '',
										endStep: step,
										endKcal: kcal,
										endTime: new Date().getTime()
									})
									uni.$emit("stepcount")
								}
							}
						}
					} else if (result[4] === '91') {
						console.log('充电状态:' + bitArr[6].toString(10))
						console.log('电量百分比：' + bitArr[7].toString(10))
						that.ActionElectric({
							state: bitArr[6].toString(10),
							percent: bitArr[7].toString(10),
							deviceId: bluedata.deviceId
						})
					} else if (result[4] === '92') {
						console.log('固件主版本号:' + bitArr[6].toString(10))
						console.log('固件副版本号：' + bitArr[7].toString(10))
						console.log('手环型号：' + bitArr[8].toString(10))
						let params = {
							equipmentArticle: bitArr[6].toString(10),
							equipmentModel: bitArr[8].toString(10)
						}
						UpdateDevice({
							...params,
							deviceId: bluedata.deviceId
						}).then((res) => {
							console.log(res)
							that.ActionDeviceList()
						})
					}
				})
			},
			// ArrayBuffer转16进度字符串示例
			ab2hex(buffer) {
				const hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				const bitArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return bit
					}
				)
				return {
					hexArr,
					bitArr
				}
			},
			timerController() {
				let that = this
				setTimeout(() => {
					that.timerController()
					let device = storage.getCurrentDevice()
					if (!device) {} else {
						// 同步数据
						that.WriteBlueTooth('tongbu')
					}
				}, 15 * 60 * 1000)
			},
		}
	}
</script>

<style lang="scss">
	/*每个页面公共css */
	page {
		height: 100%;
		background-color: #ffffff;
		color: #2b2b2b;
	}

	button {

		&:after {
			border: none;
		}
	}

	.outer-wrapper {
		height: 100%;
		box-sizing: border-box;

		&.has-bottom {
			padding-bottom: 100upx;
		}

		&.has-top {
			padding-top: 100upx;
		}
	}

	.loading {
		padding: 80upx 0;
		text-align: center;
	}

	.empty {
		text-align: center;

		image {
			margin: 0 auto;
			width: 500upx;
			height: 500upx;
		}
	}

	.u-form-item__body__left__content__label {
		white-space: nowrap;
		width: 180upx !important;
		height: 40upx;
	}

	.u-form-item__body {
		width: 600upx !important;
	}
</style>
